<template>
<div class="box">
<transition
      v-for="flyer in flyers"
      :key="flyer.id"
      name="flyerslist"
      @appear="appear"
      @after-appear="afterAppear">
      <div
        v-if="flyer.show"
        class="flyer"
        :data-id="flyer.id"
        :style="{transform: `translate3d(${flyer.x}px, ${flyer.y}px, 0)`}" v-html="flyer.domNode"></div>
    </transition>
</div>   
</template>
<script>
export default {
  data() {
    return {
      flyers: [],
      speed: -20,
      target: { x: 0, y: 0 }
    };
  },
  methods: {
    add: function(x, y, ele) {
      let flyers = this.flyers;
      flyers.push({
        id: new Date().getTime() + "",
        x,
        y,
        show: true,
        domNode: ele
      });
    },
    move(el, x, y, a, done) {
      let style = el.style;
      // 记录下起始点坐标
      let sx = x;
      let sy = y;
      let _this = this;
      if (sx > 900) {
         this.speed = -54; 
      } else if (sx > 600) {
        this.speed = -38;
      }
      let moveFn = (x, y) => {
        requestAnimationFrame(() => {
          style.transform = `translate3d(${x}px, ${y}px, 0)`;
          if (y < _this.target.y) {
            y = a * Math.pow(x - sx, 2) + sy;
            x += _this.speed;
            moveFn(x, y);
          } else {
            console.log("done");
            done();
          }
        });
      };
      moveFn(x, y);
    },
    appear(el, done) {
      let flyers = this.flyers;
      let target = this.target;
      let id = el.dataset.id;
      let x, y;
      for (let i = 0; i < flyers.length; i++) {
        if (flyers[i].id === id) {
          x = flyers[i].x;
          y = flyers[i].y;
          break;
        }
      }
      // let {x, y} = flyers[id]
      // 假设抛物线顶点在原点，则抛物线方式为 y = a*Math.pow(x-h, 2) + k，
      // 其中(h,k)即为抛物线顶点坐标
      let a = (target.y - y) / Math.pow(target.x - x, 2);
      this.move(el, x, y, a, done);
      // done()
    },
    afterAppear: function(el) {
      let flyers = this.flyers;
      let id = el.dataset.id;
      console.log("afterEnter", id);
      // 隐藏小球
      for (let i = 0; i < flyers.length; i++) {
        if (flyers[i].id === id) {
          flyers[i].show = false;
          break;
        }
      }
      this.$emit('ShopCart');
    },
    setTarget: function(target) {
      this.target = target;
    }
  }
};
</script>
<style lang="stylus">
.box
   position: absolute;
.flyer 
    position: absolute;
    width: 0.28rem;
    height: 0.28rem;
    z-index 1000
    display flex;
</style>
